#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import os
import sys

from bzjsons import Jsoner
from tests.dumps_test import Customer, Goods, Tag, SalesOrder

__project_ = 'bzjsons'
__file_name__ = 'performance_test_manually'
__author__ = 'bright.zhang'
__time__ = '2020/6/29 9:54'


def dumps_performance_test_simple_object():
    c = Customer(customer_id=100, name='Bright.Zhang', tel='15986429858', addr='Guangzhou')
    loop_count = 10000000
    started = datetime.datetime.now()
    for i in range(1, loop_count + 1):
        Jsoner.dumps(c)
    stopped = datetime.datetime.now()
    total_spent = stopped - started
    total_microseconds = round(total_spent.total_seconds() * 1000000, 0)
    avg_microseconds = total_microseconds / loop_count
    report_lines = ['============================================',
                    'Report of the performance testing for Jsoner.dumps.',
                    '============================================',
                    'dumps count: %d' % loop_count,
                    'object\'s size (byte): %s' % sys.getsizeof(c),
                    'json size (byte):%s' % sys.getsizeof(Jsoner.dumps(c)),
                    'started at: %s' % started.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'stopped at: %s' % stopped.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'total_spent (timedelta): %s' % total_spent,
                    'total micro-seconds for %d records: %s' % (loop_count, total_microseconds),
                    'micro-seconds per dumps: %s' % avg_microseconds,
                    '============================================']

    for line_str in report_lines:
        print(line_str)

    cur_dir = os.path.realpath(os.path.dirname(__file_name__))
    report_dir = os.path.join(cur_dir, 'report')
    method_name = sys._getframe().f_code.co_name
    report_name = '%s-%s.txt' % (method_name, datetime.datetime.now().strftime('%Y%m%d%H%M'))
    full_report_name = os.path.join(report_dir, report_name)
    print('full_report_name:', full_report_name)
    with open(full_report_name, 'w') as f:
        for line_str in report_lines:
            f.write(line_str)
            f.write('\r\n')


def dumps_performance_test_complex_object():
    customer01 = Customer('C001', 'bright', '1372388888', '广州')
    goods1_1 = Goods('G001', '海苔', 25.00)
    shiwu = Tag(0, '食物', True)
    lingshi = Tag(1, '零食', True)
    goods1_1.tags = [shiwu, lingshi]
    goods1_2 = Goods('G002', '手机', 2588.00)
    _3c = Tag(11, '3C', True)
    goods1_2.tags = [_3c]
    so = SalesOrder('SO-001', customer01, [goods1_1, goods1_2], 8200.38, datetime.datetime.now())

    loop_count = 1000000
    started = datetime.datetime.now()
    for i in range(1, loop_count + 1):
        Jsoner.dumps(so)
    stopped = datetime.datetime.now()
    total_spent = stopped - started
    total_microseconds = round(total_spent.total_seconds() * 1000000, 0)
    avg_microseconds = total_microseconds / loop_count
    report_lines = ['============================================',
                    'Report of the performance testing for Jsoner.dumps.',
                    '============================================',
                    'dumps count: %d' % loop_count,
                    'object\'s size (byte): %s' % sys.getsizeof(so),
                    'json size (byte):%s' % sys.getsizeof(Jsoner.dumps(so)),
                    'started at: %s' % started.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'stopped at: %s' % stopped.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'total_spent (timedelta): %s' % total_spent,
                    'total micro-seconds for %d records: %s' % (loop_count, total_microseconds),
                    'micro-seconds per dumps: %s' % avg_microseconds,
                    '============================================']

    for line_str in report_lines:
        print(line_str)

    cur_dir = os.path.realpath(os.path.dirname(__file_name__))
    report_dir = os.path.join(cur_dir, 'report')
    method_name = sys._getframe().f_code.co_name
    report_name = '%s-%s.txt' % (method_name, datetime.datetime.now().strftime('%Y%m%d%H%M'))
    full_report_name = os.path.join(report_dir, report_name)
    print('full_report_name:', full_report_name)
    with open(full_report_name, 'w') as f:
        for line_str in report_lines:
            f.write(line_str)
            f.write('\r\n')


def dumps_performance_test_complex_object_list():
    customer01 = Customer('C001', 'bright', '1372388888', '广州')
    goods1_1 = Goods('G001', '海苔', 25.00)
    shiwu = Tag(0, '食物', True)
    lingshi = Tag(1, '零食', True)
    goods1_1.tags = [shiwu, lingshi]
    goods1_2 = Goods('G002', '手机', 2588.00)
    _3c = Tag(11, '3C', True)
    goods1_2.tags = [_3c]
    so = SalesOrder('SO-001', customer01, [goods1_1, goods1_2], 8200.38, datetime.datetime.now())
    so_list = []
    for i in range(100):
        so_list.append(so)

    loop_count = 10000
    started = datetime.datetime.now()
    for i in range(1, loop_count + 1):
        Jsoner.dumps(so_list)
    stopped = datetime.datetime.now()
    total_spent = stopped - started
    total_microseconds = round(total_spent.total_seconds() * 1000000, 0)
    avg_microseconds = total_microseconds / loop_count
    report_lines = ['============================================',
                    'Report of the performance testing for Jsoner.dumps.',
                    '============================================',
                    'dumps count: %d' % loop_count,
                    'object\'s size (byte): %s' % sys.getsizeof(so_list),
                    'json size (byte):%s' % sys.getsizeof(Jsoner.dumps(so_list)),
                    'started at: %s' % started.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'stopped at: %s' % stopped.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'total_spent (timedelta): %s' % total_spent,
                    'total micro-seconds for %d records: %s' % (loop_count, total_microseconds),
                    'micro-seconds per dumps: %s' % avg_microseconds,
                    '============================================']

    for line_str in report_lines:
        print(line_str)

    cur_dir = os.path.realpath(os.path.dirname(__file_name__))
    report_dir = os.path.join(cur_dir, 'report')
    method_name = sys._getframe().f_code.co_name
    report_name = '%s-%s.txt' % (method_name, datetime.datetime.now().strftime('%Y%m%d%H%M'))
    full_report_name = os.path.join(report_dir, report_name)
    print('full_report_name:', full_report_name)
    with open(full_report_name, 'w') as f:
        for line_str in report_lines:
            f.write(line_str)
            f.write('\r\n')


def loads_performance_test_simple_object():
    c_json = '{\"customer_id\": 100, \"name\": \"Bright.Zhang\", \"tel\": \"15986429858\", \"addr\": \"Guangzhou\"}'
    loop_count = 10000000
    started = datetime.datetime.now()
    for i in range(1, loop_count + 1):
        Jsoner.loads_as_instance(c_json, cls=Customer)
    stopped = datetime.datetime.now()
    total_spent = stopped - started
    total_microseconds = round(total_spent.total_seconds() * 1000000, 0)
    avg_microseconds = total_microseconds / loop_count
    report_lines = ['============================================',
                    'Report of the performance testing for Jsoner.loads_as_instance.',
                    '============================================',
                    'loads count: %d' % loop_count,
                    'json\'s size (byte): %s' % sys.getsizeof(c_json),
                    'object\'s (byte):%s' % sys.getsizeof(Jsoner.dumps(c_json)),
                    'started at: %s' % started.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'stopped at: %s' % stopped.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'total_spent (timedelta): %s' % total_spent,
                    'total micro-seconds for %d records: %s' % (loop_count, total_microseconds),
                    'micro-seconds per dumps: %s' % avg_microseconds,
                    '============================================']

    for line_str in report_lines:
        print(line_str)

    cur_dir = os.path.realpath(os.path.dirname(__file_name__))
    report_dir = os.path.join(cur_dir, 'report')
    method_name = sys._getframe().f_code.co_name
    report_name = '%s-%s.txt' % (method_name, datetime.datetime.now().strftime('%Y%m%d%H%M'))
    full_report_name = os.path.join(report_dir, report_name)
    print('full_report_name:', full_report_name)
    with open(full_report_name, 'w') as f:
        for line_str in report_lines:
            f.write(line_str)
            f.write('\r\n')


def loads_performance_test_complex_object():
    c_json = '{\"order_id\": \"SO-001\", \"customer\": {\"customer_id\": \"C001\", \"name\": \"bright\", \"tel\": \"1372388888\", \"addr\": \"广州\"}, \"goods\": [{\"goods_id\": \"G001\", \"goods_name\": \"海苔\", \"price\": 25.0, \"tags\": [{\"tag_id\": 0, \"tag_name\": \"食物\", \"enabled\": true}, {\"tag_id\": 1, \"tag_name\": \"零食\", \"enabled\": true}]}, {\"goods_id\": \"G002\", \"goods_name\": \"手机\", \"price\": 2588.0, \"tags\": [{\"tag_id\": 11, \"tag_name\": \"3C\", \"enabled\": true}]}], \"amount\": 8200.38, \"on\": \"2020-06-29 13:37:28\", \"deleted\": false}'
    loop_count = 10000000
    started = datetime.datetime.now()
    kw = dict()
    kw["customer"] = Customer
    kw["goods"] = Goods
    kw["tags"] = Tag

    for i in range(1, loop_count + 1):
        Jsoner.loads_as_instance(c_json, cls=SalesOrder, **kw)
    stopped = datetime.datetime.now()
    total_spent = stopped - started
    total_microseconds = round(total_spent.total_seconds() * 1000000, 0)
    avg_microseconds = total_microseconds / loop_count
    report_lines = ['============================================',
                    'Report of the performance testing for Jsoner.loads_as_instance.',
                    '============================================',
                    'loads count: %d' % loop_count,
                    'json\'s size (byte): %s' % sys.getsizeof(c_json),
                    'object\'s (byte):%s' % sys.getsizeof(Jsoner.dumps(c_json)),
                    'started at: %s' % started.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'stopped at: %s' % stopped.strftime('%Y-%m-%d %H:%M:%S.%f'),
                    'total_spent (timedelta): %s' % total_spent,
                    'total micro-seconds for %d records: %s' % (loop_count, total_microseconds),
                    'micro-seconds per dumps: %s' % avg_microseconds,
                    '============================================']

    for line_str in report_lines:
        print(line_str)

    cur_dir = os.path.realpath(os.path.dirname(__file_name__))
    report_dir = os.path.join(cur_dir, 'report')
    method_name = sys._getframe().f_code.co_name
    report_name = '%s-%s.txt' % (method_name, datetime.datetime.now().strftime('%Y%m%d%H%M'))
    full_report_name = os.path.join(report_dir, report_name)
    print('full_report_name:', full_report_name)
    with open(full_report_name, 'w') as f:
        for line_str in report_lines:
            f.write(line_str)
            f.write('\r\n')


if __name__ == '__main__':
    # dumps_performance_test_simple_object()
    # dumps_performance_test_complex_object()
    # dumps_performance_test_complex_object_list()
    # loads_performance_test_simple_object()
    loads_performance_test_complex_object()
